from django.shortcuts import render
from django.shortcuts import HttpResponse
import json,time
from db.mydb import MyDBConnection
from db.dao.students import Students
from db.utils.dfutils import load_json_to_object
from db.utils.logutils import LogUtils
from db.dao.player import Player
from db.dao.education_logs import Education_logs


def students_index(request):
    current = 1#如果用户不提供，默认看第一页
    pagesize = 5#如果用户不提供，默认每页5条
    if request.method == 'GET':  #大小写
        myDBConnection = MyDBConnection()
        current = request.GET.get("current")
        pagesize = request.GET.get("pagesize")
        print(f'1111 {request.GET.get("current")}')
        offset = (int(current) - 1) * int(pagesize) #计算每页的第一条编号
        studentss_json = myDBConnection.fetch_data_by_sql(f"select * from students limit {offset},{pagesize}")
        msg = f'现在查看的是第{current}页，每页大小{pagesize}'
        print(studentss_json)
        code = 200
        rep_json =  {"code":code,"msg":msg,"students":studentss_json}
    if bool(request.GET.get('json'))==True: #判定返回是json还是页面渲染
        return HttpResponse(json.dumps(rep_json), content_type="application/json")
    else:
        return render(request, "students/index.html", rep_json)


def students_add(request):
    data = request.body.decode("utf-8")
    # print(type(data))
    myDBConnection =MyDBConnection()
   # students_json_obj = json.loads(data)
    students_json_obj=json.loads(data)
    print(students_json_obj)
    students = load_json_to_object(students_json_obj,Students())
    print(type(students))
    myDBConnection.insert_entity(students)
    pname = students.st_name
    print(pname)

    # ------------日志记录开始 ，使用自定义日志记录器LogUtils.log----------
    # path_name = '/usr/ftp/logs/students/'
    path_name = 'd:/log'
    current_time = time.localtime(time.time())

    current_time_str = time.strftime('%Y-%m-%d', current_time)  # 参数2为格式化字符串
    print(current_time_str)
    file_name = current_time_str + '_students.log'
    LogUtils.log(path_name, file_name,students.format_str())
    # LogUtils.log(path_name,file_name)


    msg = f"{pname}用户添加成功"
    code = 200
    rep_json = {"code":code,"msg":msg}
    return HttpResponse(json.dumps(rep_json,ensure_ascii=False))



# 教育经历（st_id）和学生（st_id）关联查询 学生 分页
def get_students_with_education_logs(request):
    mywhere = []
    st_id = request.GET.get("st_id")
    myDBConnection = MyDBConnection()  # 连接数据库
    current = request.GET.get("current")
    pagesize = request.GET.get("pagesize")

    offset = (int(current) - 1) * int(pagesize)  # 计算每页的第一条编号
    # ---------关联查询结果 分页------------#
    # 获取教育经历记录列表
    education_logs_json = myDBConnection.fetch_data_by_sql(
        f"select * from education_logs where st_id ='{st_id}'  limit {offset},{pagesize}")
    code = 200
    msg = f'现在查看的是受教育经历第{current}页，每页大小{pagesize}'
    rep_json = {"code": code, "msg": msg, "education_logs": education_logs_json}
    if bool(request.GET.get('json')) == True:
        return HttpResponse(json.dumps(rep_json, ensure_ascii=False), content_type="application/json")
    else:
        return render(request, "player/index.html", rep_json)

def get_studentById(request):
    mywhere = []
    st_id = request.GET.get("st_id")
    myDBConnection = MyDBConnection()  # 连接数据库


    # 获取教育经历记录列表
    student_json = myDBConnection.fetch_data_by_sql(
        f"select * from students where st_id ='{st_id}'  ")
    code = 200
    msg = f'现在查看的是受{st_id}成功'
    rep_json = {"code": code, "msg": msg, "student": student_json}
    if bool(request.GET.get('json')) == True:
        return HttpResponse(json.dumps(rep_json, ensure_ascii=False), content_type="application/json")
    else:
        return render(request, "player/index.html", rep_json)


# def get_player_with_join_records(request):
#     mywhere = []
#     p_id = request.GET.get("p_id")
#     myDBConnection = MyDBConnection()  # 连接数据库
#     current = request.GET.get("current")
#     pagesize = request.GET.get("pagesize")
#
#     offset = (int(current) - 1) * int(pagesize)  # 计算每页的第一条编号
#     # ---------关联查询结果 分页------------#
#     # 获取比赛事件记录列表
#     join_records_json = myDBConnection.fetch_data_by_sql(
#         f"select * from join_records where p_id ={p_id}  limit {offset},{pagesize}")
#     code = 200
#     msg = f'现在查看的是第{current}页，每页大小{pagesize}'
#     rep_json = {"code": code, "msg": msg, "game_events": join_records_json}
#     if bool(request.GET.get('json')) == True:
#         return HttpResponse(json.dumps(rep_json, ensure_ascii=False), content_type="application/json")
#     else:
#         return render(request, "player/index.html", rep_json)
